package cn.project.engineering.service;

import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.text.format.DateUtils;

import androidx.annotation.RequiresApi;

import com.jeremyliao.liveeventbus.LiveEventBus;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

import cn.project.engineering.constant.LiveEventBusConstant;
import cn.project.engineering.http.HttpClient;
import cn.project.engineering.http.RequestCallback;
import cn.project.engineering.http.bean.ApkInfo;
import cn.project.engineering.http.bean.RequestError;
import cn.project.engineering.http.bean.ScreenControlInfo;
import cn.project.engineering.http.bean.YvminInfo;
import cn.project.engineering.utils.AppUtils;
import cn.project.engineering.utils.IpAddressUtils;
import cn.project.engineering.utils.WonderSp;
import kotlin.jvm.JvmStatic;
import log.KLog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class LoopJobService extends JobService {
    private  static  final String TAG="DaemonJobService";
    /**
     * 刷新数据间隔时间 30s
     */
    private  static  final long DATA_REFRESH_TIME=30 * DateUtils.SECOND_IN_MILLIS;

    private  static JobScheduler jobScheduler;
    private  static Context mc;
    public static void startDaemon(Context mcontext){
        mc=mcontext;
         jobScheduler= (JobScheduler) mcontext.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        JobInfo.Builder builder=new JobInfo.Builder(10,new ComponentName(mcontext.getPackageName(), LoopJobService.class.getName())).setPersisted(true);
        //小于7.0  定时器?
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            builder.setPeriodic(DATA_REFRESH_TIME);
        } else {
            //延迟执行任务
            builder.setMinimumLatency(DATA_REFRESH_TIME);
        }

        if(jobScheduler!=null){
            jobScheduler.schedule(builder.build());
        }
    }
    public  static void stopDaemon(Context mConteant){
        jobScheduler.cancelAll();

    }
    private boolean isStop=false;
    @Override
    public boolean onStartJob(JobParameters params) {
        //如果7.0以上 轮训
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            startDaemon(this);
        }
        KLog.d(TAG+"屏幕", "轮训"+System.currentTimeMillis()+"");
        if (!WonderSp.getDataNomal(mc,"yuming").equals("")){
            checkScreenControl();
            checkUp();
        }
        return false;
    }

    /**
     * 当收到 取消请求时,该方法是系统用来挂起的任务的
     * 当ondtopjod 返回false,则系统会假设没有当前的任务,故不会调用该方法.
     * @param params
     * @return
     */
    @Override
    public boolean onStopJob(JobParameters params) {
        if (isStop){
            return  true;
        }else {
            return  false;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    //息屏和唤醒
    private void checkScreenControl() {
        KLog.d("屏幕", "屏幕");
        HttpClient.httpService().getScreenControlInfo("SellOrderSearch","1004",IpAddressUtils.getMacAddress(),"ls5Lf2VnWs9s6VEdnwYXVQ==").enqueue(new Callback<List<ScreenControlInfo>>() {

            @Override
              public void onResponse(Call<List<ScreenControlInfo>> call, Response<List<ScreenControlInfo>> response) {
                List<ScreenControlInfo> body = response.body();
                if (body.size()==0){
                        return;
                    }
                  ScreenControlInfo screenControlInfo = body.get(0);
//                KLog.d("屏幕", "屏幕22222");
//                KLog.d("屏幕", "屏幕22222"+WonderSp.getDataSop(mc));
//                  KLog.d(TAG, "轮训"+WonderSp.getDataSop(mc)+"");
                  //无sop
//                  if (WonderSp.getDataSop(mc)==1){
//                      return;
//                  }
                  KLog.d("屏幕", "屏幕"+screenControlInfo.getIsScreen());
                  if (screenControlInfo.getIsScreen()==0){
                      // 开启屏幕

                      KLog.d("屏幕", "打开屏幕");
                      LiveEventBus.get(LiveEventBusConstant.OPEN_SCREEN_EVENT).post("");
                      WonderSp.setData(mc,0);

                  }

                  if (screenControlInfo.getIsScreen()==1){
                      // 关闭屏幕
                      KLog.d("屏幕", "关闭屏幕");
                      LiveEventBus.get(LiveEventBusConstant.CLOSE_SCREEN_EVENT).post("");

                      WonderSp.setData(mc,1);
                  }

              }

              @Override
              public void onFailure(Call<List<ScreenControlInfo>> call, Throwable t) {
                  KLog.d("屏幕", "屏幕onFailure"+t.getMessage());

              }

          });

    }

    private  void  checkUp(){
        HttpClient.httpService().checkApk("SellOrderSearch","1006","ls5Lf2VnWs9s6VEdnwYXVQ==").enqueue(
                new RequestCallback<List<ApkInfo>>() {
                    @Override
                    public void onRequestSuccess(@Nullable List<ApkInfo> body) {


                    }

                    @Override
                    public void onRequestFail(@NotNull RequestError error) {

                    }

                    @Override
                    public void onFailure(@NotNull Call<List<ApkInfo>> call, @NotNull Throwable t) {

                    }

                    @Override
                    public void onResponse(@NotNull Call<List<ApkInfo>> call, @NotNull Response<List<ApkInfo>> response) {
                        List<ApkInfo> body = response.body();
                        if (body.size()==0){
                            return;
                        }
                        if (Integer.valueOf(body.get(0).getUnitName())>AppUtils.getVersionCode(mc)){
                            LiveEventBus.get(LiveEventBusConstant.UPDATE).post(""+body.get(0).getAPK());
                        }
                    }
                }
        );


    }


    private void  checkInter(){
        KLog.d(TAG, "checkInter");
        HttpClient.httpService().checkYvmian("SellOrderSearch","1014","ls5Lf2VnWs9s6VEdnwYXVQ==").enqueue(new RequestCallback<List<YvminInfo>>() {
            @Override
            public void onResponse(@NotNull Call<List<YvminInfo>> call, @NotNull Response<List<YvminInfo>> response) {
                KLog.d(TAG, "暂无网络onResponse");

            }

            @Override
            public void onFailure(@NotNull Call<List<YvminInfo>> call, @NotNull Throwable t) {
                LiveEventBus.get(LiveEventBusConstant.INTERNET).post("");
                KLog.d(TAG, "暂无网络onFailure");

            }

            @Override
            public void onRequestSuccess(@Nullable List<YvminInfo> body) {

                KLog.d(TAG, "暂无网络onRequestSuccess");



            }

            @Override
            public void onRequestFail(@NotNull RequestError error) {
                LiveEventBus.get(LiveEventBusConstant.INTERNET
                ).post("");
                KLog.d(TAG, "暂无网络onRequestFail");

            }
        });


    }


}
